﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Threading.Tasks;
using TestApp.Model;
using TestApp.WebService.Parsers;



namespace TestApp.WebService
{
    public sealed class CouponsService
    {
        private static volatile CouponsService instance;
        private static object syncRoot = new Object();

        private CouponsService() { }

        // Singleton Instance
        public static CouponsService Instance
        {
            get 
            {
                 if (instance == null) 
                 {
                    lock (syncRoot) 
                    {
                       if (instance == null)
                           instance = new CouponsService();
                    }
                 }

                 return instance;
           }
         }

        // Fetch Coupons
        public async Task<List<Coupon>> FetchCoupons()
        {
            // Set the URL
            string URL = @"https://service.mywebgrocer.com/coupons/v3/139/fsn/43010508144?filterBy=all&target=all";
            string authorization = @"BA280030-1118-4930-878E-73710686BC2D";

            // Get the response
            WSResponse response = await WSManager.Instance.ExecuteRequest(HttpMethod.GET, URL, null, authorization, null, null).ConfigureAwait(false);

            // Create the parser and hanlde the response data
            Parser parser = new CouponsParser();

            if (response.StatusCode == HttpStatusCode.OK)
            {
                // Success
                return parser.ParseResults(response) as List<Coupon>;
            }
            else
            {
                // Throw WSException
                throw parser.ParseError(response);
            }
           
        }
    }
}
